package com.example.news.service.impl;

import com.example.news.mapper.RedisDao;
import com.example.news.pojo.User;
import com.example.news.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisDao redisDao;

    @Override
    public List<User> getAllUser() {
        List<User> userList = new ArrayList<>();
        //根据user:*筛选出符合条件的key(是个set集合)
        Set<String> keys = redisDao.keys("user:*");
        for (String key : keys) {
            Map<Object, Object> map = redisDao.getAllMap(key);
            String uid = key.substring(key.indexOf(":") + 1);
            String count = (String) map.get("count");
            Integer zcount = count == null ? 0 : Integer.parseInt(count);
            //1.从redis的hash中取出uid和票数存放到zset里
            redisDao.zsetSetAll("user-zset", uid, zcount);
        }
        //2.zset倒序排序并取出uid顺序
        Set<String> sortedUid = redisDao.reverseRange("user-zset", 0, -1);
        //3.根据排序后的uid顺序获取每一个实例对象，并将对象存入List集合返回
        for(String k : sortedUid){
            String key = "user:" + k;
            Map<Object, Object> map = redisDao.getAllMap(key);
            User user = new User();
            user.setUid(Integer.parseInt(k));
            user.setName((String)map.get("name"));
            user.setAge(Integer.parseInt((String)map.get("age")));
            user.setSex((String)map.get("sex"));
            String count = (String)map.get("count");
            user.setCount(count == null?0:Integer.parseInt(count));
            userList.add(user);
        }
        return userList;
    }

    @Override
    public Integer addCount(Integer uid) {
        String key = "user:" + uid;
        return redisDao.hashIncr(key, "count");
    }

}
